﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using System.IO;
using System.Windows.Media;
using ThreeByte.Media;

namespace ThreeByte.ActiveDeck.Config
{

    

    public class GraphicResourceWrapper : GraphicResource
    {
        public object StorageRoot { get; private set; }

        public delegate byte[] GetBytesDelegate(object storageRoot, Guid id);
        //public delegate Guid SetBytesDelegate(byte[] graphicBytes, Guid id, string name, ImageType type);

        public override byte[] GraphicBytes {
            get {
                //This uses the delegate to retrieve the image bytes on demand
                return GetBytes(StorageRoot, ID);
            }
            //protected set {
            //    //This uses the delegate to store the image bytes on demand
            //    ID = SetBytes(value, ID, Name, ImageType);
            //}
        }

        public static GetBytesDelegate GetBytes {
            get;
            set;
        }

        //public static SetBytesDelegate SetBytes {
        //    get;
        //    set;
        //}

        #region Constructors
        private GraphicResourceWrapper() : base() {
            ImageType = ImageType.PNG;
        }

        private GraphicResourceWrapper(Guid id, string name, ImageType imageType = ImageType.PNG)
            : this() {
            ID = id;
            Name = name;
            ImageType = imageType;
        }

        #endregion Constructors

        public static GraphicResourceWrapper FromXml(object storageRoot, XElement node) {
            Guid id = Guid.Parse(node.Attribute("ID").Value);
            string name = node.Attribute("Name").Value;
            //string encodedImageString = node.Value;
            ImageType type = ImageType.PNG;
            if(node.Attribute("Type") != null && node.Attribute("Type").Value == "JPEG") {
                type = ImageType.JPEG;
            }
            string hash = null;
            if(node.Attribute("MD5") != null) {
                hash = node.Attribute("MD5").Value;
            }

            GraphicResourceWrapper res = new GraphicResourceWrapper(id, name, type) { StorageRoot = storageRoot, Hash = hash};
            //Allow the hash to be re-calculated if it wasn't previously stored.  This is really only to support
            //transitional backwards compatibility for when Hashes were not stored explicitly in the header info
            if(res.Hash == null) {
                res.Hash = GenerateHash(res.GraphicBytes);
            }
            return res;
        }
    }
}
